package org.example.memora.controller;

import org.example.memora.Repository.ChatHistoryRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.example.memora.DTO.ChatForm;
import org.example.memora.DTO.UserRedisDTO;
import org.example.memora.common.utils.ChatContext;
import org.example.memora.common.utils.UserHolder;
import org.example.memora.entity.ChatMessageDocument;
import org.example.memora.service.XiaoyouAgent;

import org.example.memora.store.MongoChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.util.context.Context;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "小邮")
@RestController
@RequestMapping("/xiaoyou")
public class XiaoyouController {

    @Autowired
    private XiaoyouAgent xiaoyouAgent;
    @Autowired
    private MongoChatMemoryStore mongoChatMemoryStore;
    @Autowired
    private  ChatHistoryRepository chatHistoryRepository;


    @Operation(summary = "对话")
    @PostMapping(value = "/chat", produces = "application/json;charset=utf-8")
    public String chat(@RequestBody ChatForm chatForm) {
        //  此处拿到 user
        UserRedisDTO user = UserHolder.getUser();
        chatHistoryRepository.save("chat", String .valueOf(chatForm.getMemoryId()));
        // 提前存到 ChatContext（ThreadLocal 代理）
        ChatContext.setCurrentUserId(String.valueOf(user.getUserId()));
        String s=String.valueOf(user.getUserId());
        // 你自定义的 ThreadLocal
        return xiaoyouAgent.chat(chatForm.getMemoryId(), chatForm.getMessage(),s);
    }
    @Operation(summary = "分页查询历史记录")
    @GetMapping("/history")
    public Map<String, Object> getChatHistory(
            @RequestParam String memoryId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {

        // 拿到当前用户ID
        String userId = String.valueOf(UserHolder.getUser().getUserId());

        // 查询数据
        List<ChatMessageDocument> docs = mongoChatMemoryStore.getUserAiMessagesPaged(memoryId, userId, page, pageSize);
        long total = mongoChatMemoryStore.countUserAiMessages(memoryId, userId);

        // 转换为前端需要的格式
        List<Map<String, Object>> records = docs.stream().map(doc -> {
            Map<String, Object> map = new HashMap<>();
            map.put("type", doc.getType());
            map.put("text", doc.getText());
            map.put("createTime", doc.getCreateTime());
            return map;
        }).collect(Collectors.toList());

        // 封装分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("hasNext", page * pageSize < total);

        return result;
    }
    @Operation(summary = "查询会话ID列表", description = "根据业务类型查询对应的会话ID列表，如 chat、service、pdf")
    @GetMapping("/ai/history/{type}")
    public List<String> getChatIds(
            @Parameter(description = "业务类型，如：chat、service、pdf", required = true)
            @PathVariable("type") String type
    ) {
        return chatHistoryRepository.getChatIds(type);
    }
    @Operation(summary = "开启新会话", description = "生成新的 memoryId，用于开启一次新的智能对话")
    @GetMapping("/new")
    public Map<String, String> startNewChat() {
        // 生成唯一的 memoryId（UUID 字符串）
        String memoryId = java.util.UUID.randomUUID().toString();

        // 当前用户 ID
        String userId = String.valueOf(UserHolder.getUser().getUserId());

        // 可选：记录该 memoryId 到 history 中（用于查询）
        chatHistoryRepository.save("chat", memoryId);

        // 返回结果给前端
        Map<String, String> result = new HashMap<>();
        result.put("memoryId", memoryId);
        return result;
    }


}
